Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

HashMap → Java HashMap

HashMap

Java HashMap

HashMap in Java collections

HashMap is a popular implementation of the Map interface in Java's collections framework. It provides an efficient way to store key-value pairs. Unlike ordered collections (like lists), HashMap focuses on fast access and retrieval of elements based on unique keys.

Characteristics of HashMap

Key-Value Pairs: HashMap stores elements as key-value pairs. Each key is unique and acts as an index to its corresponding value. ⯁ Hashing: It uses a hashing technique for efficient storage and retrieval. The key's hashCode() method is used to calculate a hash code, which determines the bucket (position) in the internal hash table where the key-value pair is stored. ⯁ Uniqueness: Keys must be unique within a HashMap. Attempting to add a duplicate key will overwrite the existing value associated with that key. ⯁ Null Keys and Values: HashMap allows storing a single null key and any number of null values.

Declaring and Initializing HashMaps

Import
HashMap import syntax import java.util.HashMap;
This line imports the HashMap class from the java.util package.
Declaration
HashMap declaration HashMap<KeyType, ValueType> myMap;
This declares a variable named myMap of type HashMap. The <KeyType> and <ValueType> placeholders specify the data types of the keys and values, respectively.
Initialization Default constructor
Default constructor - empty hashmap myMap = new HashMap<KeyType, ValueType>();
This creates an empty HashMap object.
Adding initial elements during creation (Java 7+)
Creating HashMap with initial elements HashMap<String, Integer> fruits = new HashMap<String, Integer>(); fruits.put("Apple", 10); fruits.put("Banana", 15); fruits.put("Orange", 8);
This creates a HashMap and adds initial key-value pairs while constructing it.

Common HashMap Methods

put(key, value): Inserts a new key-value pair into the map. If the key already exists, the value is updated. ⯁ get(key): Returns the value associated with the given key, or null if the key doesn't exist. ⯁ containsKey(key): Checks if the map contains a specific key. ⯁ remove(key): Removes the key-value pair associated with the given key and returns the value. ⯁ isEmpty(): Checks if the map is empty. ⯁ size(): Returns the number of key-value pairs in the map.

Examples for HashMap

Basic example - Student detail
HashMap simple example - student detail import java.util.HashMap; public class Main { public static void main(String[] args) { // Create a HashMap for students (String: name, Integer: ID) HashMap<String, Integer> students = new HashMap<String, Integer>(); students.put("Sathish", 123); students.put("Mohammed", 112); students.put("Joseph", 111); int SathishId = students.get("Sathish"); System.out.println("Sathish's ID: " + SathishId); boolean hasDavid = students.containsKey("David"); System.out.println("Contains 'David': " + hasDavid); // Remove a student (using key) students.remove("Mohammed"); System.out.println(students); } }

Output

Sathish's ID: 123 Contains 'David': false {Sathish=123, Joseph=111}
Explanation : This example does simple operations using methods.
String Keys and Integer Values (Common Scenario):
Hashmap simple example import java.util.HashMap; public class Main { public static void main(String[] args) { HashMap<String, Integer> studentGrades = new HashMap<>(); studentGrades.put("Anderson", 90); studentGrades.put("Jenny", 85); studentGrades.put("Scott", 78); System.out.println(studentGrades.get("Scott")); } }

Output

78
Explanation : This example stores student names (strings) as keys and their grades (integers) as values.
Custom Object Keys and String Values
Hashmap example with hashcode to compare import java.util.*; class Product { int id; String name; public Product(int id, String name) { this.id = id; this.name = name; } @Override public int hashCode() { return this.id; // Use product ID for hashing (assuming unique IDs) } @Override public boolean equals(Object obj) { if (obj instanceof Product) { Product otherProduct = (Product) obj; return this.id == otherProduct.id; // Compare based on ID for equality } return false; } } public class Main { public static void main(String[] args) { HashMap<Product, String> productMap = new HashMap<>(); productMap.put(new Product(123, "Laptop"), "Available"); productMap.put(new Product(456, "Headphones"), "Out of stock"); Product laptopProduct = new Product(123, "Laptop"); System.out.println(productMap.get(laptopProduct)); } }

Output

Available
Explanation : This example defines a Product class with id and name attributes. It uses id in the hashCode() and equals() methods to ensure proper key functionality within the HashMap. The map stores Product objects as keys and availability information (strings) as values.
Integer Keys and Double Values
Hashmap example in java - product prices import java.util.HashMap; public class Main { public static void main(String[] args) { HashMap<Integer, Double> productPrices = new HashMap<>(); productPrices.put(101, 199.99); productPrices.put(202, 79.95); productPrices.put(303, 45.50); System.out.println(productPrices.get(202)); } }

Output

79.95
Explanation : This example uses integer product IDs as keys and their corresponding prices (doubles) as values.
String Keys and Object Values
Hashmap example with object as elements in java import java.util.HashMap; class Address { String street; String city; String state; public Address(String street, String city, String state) { this.street = street; this.city = city; this.state = state; } } public class Main { public static void main(String[] args) { HashMap<String, Address> customerAddresses = new HashMap<>(); customerAddresses.put("Antony", new Address("123 Main St", "Anytown", "CA")); customerAddresses.put("Bob", new Address("456 Elm St", "Big City", "NY")); System.out.println(customerAddresses.get("Antony").street); } }

Output

123 Main St
Explanation : This example defines an Address class to store address information. The HashMap uses strings as customer names (keys) and Address objects as values.
Remember, HashMap is flexible and can accommodate various data types for keys and values as long as the key type properly implements hashCode() and equals() for efficient hashing and comparison. Choose the data types that best suit your specific use case and data storage requirements.

Tutorials